﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Xml;
using SP_XHWeb.Layouts.SP_XHWeb;
using System.Text;

namespace SP_XHWeb.ControlTemplates.SP_XHWeb
{
    public partial class TopForum : UserControl
    {
        private string ForumUrl = System.Configuration.ConfigurationSettings.AppSettings["ForumUrl"].ToString();
        private string BlogUrl = System.Configuration.ConfigurationSettings.AppSettings["BlogUrl"].ToString();
        public string RSSTitle = "";
        public string RSSLink = "";
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                lblForum.InnerHtml = InitTopForum();
                lblBlog.InnerHtml = InitTopBlog();
            }
        }

        private string InitTopForum()
        {
            StringBuilder str = new StringBuilder();
            try
            {
                List<RSSItem> lists = GetRSSItems(ForumUrl, ref RSSTitle, ref RSSLink);
                //标题长度
                int len = 17;

                str.Append("<ul>");

                if (lists != null && lists.Count != 0)
                {
                    if (lists.Count > 6)
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            DateTime dt;
                            str.Append("<li>");
                            if (lists[i].title.Length > len)
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title.Substring(0, len) + "..." + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            else
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            str.Append("</li>");
                        }
                    }
                    else
                    {
                        for (int i = 0; i < lists.Count; i++)
                        {
                            DateTime dt;
                            str.Append("<li>");
                            if (lists[i].title.Length > len)
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title.Substring(0, len) + "..." + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            else
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            str.Append("</li>");
                        }
                    }
                }

                str.Append("</ul>");
            }
            catch
            {
                str.Append("链接失败，请确认网络连接正常");
            }
            return str.ToString();
        }

        private string InitTopBlog()
        {
            StringBuilder str = new StringBuilder();
            try
            {
                List<RSSItem> lists = GetRSSItems(BlogUrl, ref RSSTitle, ref RSSLink);
                //标题长度
                int len = 17;

                str.Append("<ul>");

                if (lists != null && lists.Count != 0)
                {
                    if (lists.Count > 6)
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            DateTime dt;
                            str.Append("<li>");
                            if (lists[i].title.Length > len)
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title.Substring(0, len) + "..." + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            else
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            str.Append("</li>");
                        }
                    }
                    else
                    {
                        for (int i = 0; i < lists.Count; i++)
                        {
                            DateTime dt;
                            str.Append("<li>");
                            if (lists[i].title.Length > len)
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title.Substring(0, len) + "..." + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            else
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i].link, lists[i].title + (!string.IsNullOrEmpty(lists[i].date) && DateTime.TryParse(lists[i].date, out dt) ? dt.ToString("【MM-dd】") : ""));
                            }
                            str.Append("</li>");
                        }
                    }
                }

                str.Append("</ul>");
            }
            catch
            {
                str.Append("链接失败，请确认网络连接正常");
            }
            return str.ToString();
        }

        public List<RSSItem> GetRSSItems(string url, ref string RSSTitle, ref string RSSLink)
        {
            XmlDocument doc = new XmlDocument();

            RequestHelper request = new RequestHelper(url);
            string rss = request.Get();

            int index = rss.IndexOf("<");
            if (index > 0) rss = rss.Substring(index);
            doc.LoadXml(rss);



            XmlNodeList nodesRSS = doc.GetElementsByTagName("title");
            if (nodesRSS.Count > 0)
            {
                RSSTitle = nodesRSS.Item(0).InnerText;
            }

            nodesRSS = doc.GetElementsByTagName("link");
            if (nodesRSS.Count > 0)
            {
                RSSLink = nodesRSS.Item(0).InnerText;
            }

            //nodesRSS = doc.GetElementsByTagName("description");
            //if (nodesRSS.Count > 0)
            //{
            //    RSSDescription = nodesRSS.Item(0).InnerText;
            //}


            List<RSSItem> items = new List<RSSItem>();

            XmlNodeList nodes = doc.GetElementsByTagName("item");

            if (nodes.Count <= 0)
            {
                nodes = doc.GetElementsByTagName("entry");
            }

            int i = 0;
            foreach (XmlNode node in nodes)
            {
                i++;
                //if (i > PostNumber)
                //    break;
                string link = string.Empty;
                string title = string.Empty;
                string date = string.Empty;

                RSSItem item = new RSSItem();

                foreach (XmlNode childNode in node.ChildNodes)
                {
                    if (childNode.Name == "link")
                    {
                        link = childNode.InnerText;
                        if (string.IsNullOrEmpty(link))
                        {
                            try
                            {
                                if (childNode.Attributes["href"] != null)
                                {

                                    link = childNode.Attributes["href"].Value;
                                }
                            }
                            catch (Exception e)
                            {
                            }
                        }

                        if (string.IsNullOrEmpty(link) == false)
                            link = link.Replace(" ", "%20");
                    }
                    else if (childNode.Name == "title")
                    {
                        title = childNode.InnerText;
                        
                    }
                    else if (childNode.Name == "pubDate")
                    {
                        date = childNode.InnerText;
                    }
                }
                
                item.link = link;
                item.date = date;
                item.title = title;
                
                items.Add(item);
            }

            return items;


        }
    }

    public class RSSItem
    {
        public string title { get; set; }

        public string link { get; set; }

        public string date { get; set; }
    }
}
